#!/usr/bin/python
import sys, pyserv, testserv

# Change this to change which server class gets used. Should be a subclass of pyserv.HTTPServer.
server = testserv.TestServ()

# Example registration (in server __init__ method)
# self.register("GET",lambda m,p,h: pyserv.abort(418))
# The above will make any GET request return the I'm a Teapot code.

# Distance from end of string to literal "HTTP". Should be 8 in all requests.
def httpDistance(l):
	return (l[::-1].find("PTTH"))+len("PTTH")

# Read all lines of data sent to us by browser/client
inlines = []
a = sys.stdin.readline().rstrip()
while a:
	inlines.append(a)
	a = sys.stdin.readline().rstrip()
# Validate HTTP request
# In all valid HTTP requests, "HTTP/X.X" is 8 characters from the end.
if httpDistance(inlines[0])!=8:
	print(pyserv.abort(400))
# Parse headers
headers = dict()
for l in inlines[1:]:
	p = l.split(": ",1)
	if p[0] in headers:
		continue
	headers[p[0]] = p[1]
# Parse request
method, path, version = inlines[0].split(" ")
# If the server doesn't have the method, it isn't implemented.
if not server.hasMethod(method):
	print(pyserv.abort(501))
if method=="POST":
	# Read query-string and call function
	print(server.methods[method](method, path, headers, sys.stdin.read(int(headers["Content-Length"]))))
else:
	# Just call the function
	print(server.methods[method](method, path, headers))
